package com.simon.study.algorithm.tree;

import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.ToString;

/**
 * <p>
 *
 * @author simon
 */
public class Array2Tree {

    public static void main(String[] args) {
        String txt = "[{\"id\":1,\"name\":\"部门1\",\"pid\":0},{\"id\":2,\"name\":\"部门2\",\"pid\":1},{\"id\":3,\"name\":\"部门3\",\"pid\":1},{\"id\":4,\"name\":\"部门4\",\"pid\":3},{\"id\":5,\"name\":\"部门5\",\"pid\":4}]";

        List<NNode> nodes = JSON.parseArray(txt, NNode.class);
        NNode root = null;
        Map<Integer,NNode> nodeMap = nodes.stream().collect(Collectors.toMap(e->e.id, e->e));
        for (NNode node : nodes) {
            NNode tar = nodeMap.get(node.pid);
            if(tar != null){
                if( tar.children == null ){ tar.children = new ArrayList<>(); }
                tar.children.add(node);
            }else{
                root = node;
            }
        }

        System.out.println(JSON.toJSONString(root));
    }



    @ToString
    public static class NNode{
        public int id;
        public int pid;

        public String name;

        public List<NNode> children;
    }
}



